<?php

namespace Gnway\Ticket\Rest\Util;

final class FileUtils
{

  /**
   * Don't let anyone instantiate this class
   */
  private function __construct() {}

  /**
   * Scan files.
   *
   * @param string $path
   * @param string $extension
   * @return array
   */
  public static function scanFiles(string $path, string $extension): array
  {
    $files = [];
    if (!is_dir($path)) {
      return $files;
    }

    $dir_handle = opendir($path);
    while (FALSE !== ($file = readdir($dir_handle))) {
      if ($file == '.' || $file == '..') {
        continue;
      }
      if (is_dir($path . '/' . $file)) {
        $files = array_merge($files, self::scanFiles($path . '/' . $file, $extension));
      } else {
        if ($extension) {
          ltrim($extension) === pathinfo($file, PATHINFO_EXTENSION) && $files[] = $path . '/' . $file;
        } else {
          $files[] = $path . '/' . $file;
        }
      }
    }
    closedir($dir_handle);

    return $files;
  }

  /**
   * Scan directory.
   *
   * @param string $path
   * @return array
   */
  public static function scanDirectory(string $path): array
  {
    $dirs = [];
    if (!is_dir($path)) {
      return $dirs;
    }

    $dir_handle = opendir($path);
    while (FALSE !== ($file = readdir($dir_handle))) {
      if ($file == '.' || $file == '..') {
        continue;
      }
      if (is_dir($filename = $path . '/' . $file)) {
        $dirs[] = $filename;
        $dirs = array_merge($dirs, self::scanDirectory($filename));
      }
    }
    closedir($dir_handle);

    return $dirs;
  }
}